﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Sio.Mdm.Server;
using Sio.Mdm.Types;

namespace IDM.Web.Base
{
    /// <summary>
    /// Session provider implementation.
    /// We intercept call to login and logout and set <see cref="Session"/> instance
    /// to ASPX session object if no error occurs when doing login.
    /// On logout we remove key from ASPX session object.
    /// </summary>
    public class SessionProvider : IInvokeInterceptor, ISessionProvider
    {
        #region ISessionProvider Members
        Session ISessionProvider.GetSession()
        {
            return HttpContext.Current.Session["__session"] as Session;
        }
        #endregion

        #region IInvokeInterceptor Members
        bool IInvokeInterceptor.BeforeInvoke(System.Reflection.MethodInfo method, object[] args, out object result)
        {
            result = null;
            return true;
        }

        void IInvokeInterceptor.AfterInvoke(System.Reflection.MethodInfo method, object[] args, object result, InvocationError error)
        {
            if (method.Name == "Login")
            {
                if (error == null)
                {
                    HttpContext.Current.Session["__session"] = args[2];
                }
                else
                {
                    HttpContext.Current.Session.Remove("__session");
                }                
            }

            if (method.Name == "Logout")
            {
                HttpContext.Current.Session.Remove("__session");
            }
        }
        #endregion
    }
}
